package com.example.recorder;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private final String TAG = MainActivity.class.getSimpleName();
    private String AUDIO_WAV_FILENAME = "FinalAudio.wav";
    private final String url = "http:/10.0.2.2:8001/";
    private TextView textResult, textTime;
    private Button btnSendRight, btnSendError;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission();
//        final AudioRecorder recorder=new AudioRecorder();
//        final ImageButton recordButton=(ImageButton) findViewById(R.id.recordButton);
//        recordButton.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                if(motionEvent.getAction()==motionEvent.ACTION_DOWN)
//                    recorder.startRecording();
//                if(motionEvent.getAction()==motionEvent.ACTION_UP) {
//                    recorder.stopRecording();
//                }
//                return false;
//            }
//        });
        final AudioRecordFunc recorder = new AudioRecordFunc();
        final ImageButton recordButton = (ImageButton) findViewById(R.id.recordButton);
        textResult = (TextView) findViewById(R.id.text_result);
        textTime = (TextView) findViewById(R.id.text_time);
        recordButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == motionEvent.ACTION_DOWN) {
                    AUDIO_WAV_FILENAME = System.currentTimeMillis() + ".wav";
                    recorder.startRecordAndFile(AUDIO_WAV_FILENAME);
                }
                if (motionEvent.getAction() == motionEvent.ACTION_UP) {
                    recorder.stopRecordAndFile();
                    upload();
                }
                return false;
            }
        });
        btnSendRight = (Button) findViewById(R.id.btn_send_right);
        btnSendRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                send("判断正确");
            }
        });
        btnSendError = (Button) findViewById(R.id.btn_send_error);
        btnSendError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                send("判断错误");
            }
        });
    }

    public void send(String str) {
        JSONObject obj = new JSONObject();
        obj.put("result", str);
        // 真机写局域网ip
        HttpUtil.post(url + "result", obj, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, e.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getBaseContext(), "发送失败，网络或接口出错！", Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    String result = response.body().string();
                    Log.d(TAG, result);
                    JSONObject data = (JSONObject) JSONObject.parse(result);
                    String message = data.getString("message");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (message.equals("success"))
                                Toast.makeText(getBaseContext(), "发送成功！", Toast.LENGTH_SHORT).show();
                            else
                                Toast.makeText(getBaseContext(), "接口出错！", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void upload() {
        File output = new File(AudioFileFunc.getWavFilePath(AUDIO_WAV_FILENAME));
        Log.d(TAG, "开始上传");
        textResult.setText("开始上传");
        // 真机写局域网ip
        HttpUtil.postFile(url + "upload", output, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, e.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textResult.setText("上传失败，网络或接口出错！");
                        textTime.setText("检测时间："+DateUtils.getStringDate());
                    }
                });

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    String result = response.body().string();
                    Log.d(TAG, result);
                    JSONObject data = (JSONObject) JSONObject.parse(result);
                    String message = data.getString("message");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (message.equals("success")) {
                                int pred = data.getInteger("pred");
                                if (pred == 1) textResult.setText("合格");
                                else textResult.setText("不合格");
                            } else textResult.setText("上传成功，解析失败"+message);
                            textTime.setText("检测时间："+DateUtils.getStringDate());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 权限申请
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, 200);
                    return;
                }
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == 200) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, 200);
                    return;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 200) {
            checkPermission();
        }
    }

}
